define(function(require, exports, module) {

	var $ = require('$'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        ContactModel = require('model/contact'),
        ContactSearchView = require('view/contact-search'),
        Users = require('data/users');

	module.exports = Backbone.View.extend({
        el: '.page[data-page=contactSearch]',
		events: {
            'click .button-submit': 'onSearch'
        },
        template: require('tpl/contact/view.handlebars'),
        viewList: [],
        initialize: function(options) {
            var self = this;
            //传入gomac
            this.gomac = options.gomac;
        },
        addOne: function(model) {
            var view = new ContactSearchView({model: model});
            $(this.el).find('.list-block-result ul').append(view.render().el);
            this.viewList.push(view);
        },
        clean: function() {
            while(this.viewList.length>0) {
                this.viewList.pop().remove();
            }
        },
        onSearch: function(e) {
            var self = this,
                input = self.$el.find('.list-block-form input[type=text]');
            var pattern = input.val();
            if(pattern.length > 0) {
                self.clean();
                //TODO: 从后台查找数据
                var data = _.filter(Users, function(obj) {
                    if(obj.nick.indexOf(pattern) >= 0 || obj.username.indexOf(pattern) >= 0) 
                        return true;
                });
                if(data.length > 1) {
                    _.each(data, function(attr) {
                        self.addOne( new ContactModel(attr) );
                    });
                }
                else if(data.length === 1) {
                    self.gomac.mainView.router.loadPage('pages/contacts/view.html?id='+data[0].objectId);
                }
                else {
                    self.gomac.alert('没有找到');
                }
                input.val('');
            }
        }
	});
});